import { Suspense, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import logoutPng from '@/assets/icon/logout.png';
import Loading from '@/components/Loading';
import EchartsView from '@/components/main/Echarts';
import ShareLink from '@/components/main/ShareLink';
import Stats from '@/components/main/Stats';
import API from '@/http';
import { useShallow } from 'zustand/shallow';
import { useAuthStore } from '@/stores/auth';
import { useNavigate } from 'react-router-dom';

function DataView({ reportData }) {
  const { t } = useTranslation();
  const {
    profit: $profit,
    download: $download,
    click: $click,
    translation: $translation,
    share_url: shareLink,
  } = reportData;

  const profit = {
    titleTop: t('totalProfitGain'),
    valueTop: $profit?.profit_total,
    titleBottom: t('todayProfitSharing'),
    valueBottom: $profit?.profit_today,
    type: $profit.type,
    percent: $profit.percent,
  };

  const download = {
    titleTop: t('totalDownloads'),
    valueTop: $download?.download_total,
    titleBottom: t('todayDownloads'),
    valueBottom: $download?.download_today,
    type: $download.type,
    percent: $download.percent,
  };

  const click = {
    titleTop: t('totalHits'),
    valueTop: $click?.click_total,
    titleBottom: t('todayHits'),
    valueBottom: $click?.click_today,
    type: $click.type,
    percent: $click.percent,
  };

  const translation = {
    titleTop: t('orderConversionRate'),
    valueTop: parseFloat($translation?.percent || '0'),
    type: $translation.type,
    percent: $translation.percent,
  };

  const [option, setOption] = useState('profit');
  const [title, setTitle] = useState('');
  useEffect(() => {
    switch (option) {
      case 'profit':
        setTitle(t('incomeStatement'));
        break;
      case 'invited_num':
        setTitle(t('totalDownloads'));
        break;
      case 'click_num':
        setTitle(t('totalHits'));
        break;
    }
  }, [option, t]);
  return (
    <>
      <ShareLink shareLink={shareLink} />
      <Stats
        callBack={setOption}
        {...{ profit, download, click, translation }}
      />
      <EchartsView option={option} title={title} />
    </>
  );
}

function Main() {
  const { t } = useTranslation();
  const [reportData, setReportData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, logout] = useAuthStore(
    useShallow((state) => [state.isAuthenticated, state.logout])
  );
  const navigate = useNavigate();
  
  useEffect(() => {
    // Fetch data only on the first render
    const fetchData = async () => {
      try {
        const data = await API.Home.report();
        setReportData(data);
      } catch (error) {
        console.error('Error fetching report data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);
  async function logoutAction() {

    try {
      await logout();
      navigate('/login');
    } catch (e) {
      console.error(e);
    }
  }
  return (
    <div className="relative bg-grey px-5 md:mx-auto pt-12 md:pt-24">
      {
        isAuthenticated() ? ( <div className=" hidden md:flex item-center z-20 px-2 py-2 text-ff bg-black w-[100px] rounded-xs cursor-pointer absolute top-20 right-28 mr-12">
          <img
            src={logoutPng}
            className="mr-2 h-[20px] w-[20px] cursor-pointer"
          />
          <div className='text-12' onClick={logoutAction}>{t('logOut')}</div>
        </div>) : ''
      }
     
      <div className="flex max-w-[1290px] flex-col items-center space-y-4 md:space-y-12">
        <h1 className="hidden text-center text-20 font-semibold leading-140 text-ff md:block md:text-30">
          {t('marketingProfitZone')}
        </h1>
        {loading ? (
          <Loading />
        ) : (
          reportData && <DataView reportData={reportData} />
        )}
      </div>
    </div>
  );
}

export default Main;
